package com.android.cameracomposit;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.usb.UsbDevice;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.lgh.uvccamera.UVCCameraProxy;
import com.lgh.uvccamera.bean.PicturePath;
import com.lgh.uvccamera.callback.ConnectCallback;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 就是要编程一个相机app
 * 里面要求有拍照功能（有两个功能接口分别调用红外光相机和可见光相机）+两个图像融合功能
 * 就是把白光和红外融合成一张图片
 */
public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private static final int LIGHT_OPEN_CAMERA_CODE = 300;

    private Button mBtnHwCamera;
    private Button mBtnLightCamera;
    private Button mBtnFusion;
    private ImageView mImgHw;
    private ImageView mImgLight;
    private ImageView mImgFusion;
    private String mLightFilePath;
    private Bitmap mHwBitmap;
    private Bitmap mLightBitmap;
    private Bitmap mFusionBitmap;
    private UVCCameraProxy mUvcCameraProxy;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        checkPermission();
        initData();
        initView();
        initListener();
    }

    private void initData() {
        // android 7.0系统解决拍照的问题
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        builder.detectFileUriExposure();

        mUvcCameraProxy = new UVCCameraProxy(this);

        mUvcCameraProxy.registerReceiver(); //注册USB插拔监听广播

        //mUvcCameraProxy配置
        mUvcCameraProxy.getConfig().isDebug(true).setPicturePath(PicturePath.APPCACHE)
                .setDirName("hwUvcPhoto");

        //设置拍照按钮点击回调
        mUvcCameraProxy.setPhotographCallback(() -> mUvcCameraProxy.takePicture());

        //设置拍照成功图片回调
        mUvcCameraProxy.setPictureTakenCallback(path -> {
            mHwBitmap = BitmapFactory.decodeFile(path);
            if (mHwBitmap != null) {
                mImgHw.setImageBitmap(mHwBitmap);
            }
        });


        //USB监听回调
        mUvcCameraProxy.setConnectCallback(new ConnectCallback() {
            @Override
            public void onAttached(UsbDevice usbDevice) {
                mUvcCameraProxy.requestPermission(usbDevice); // USB设备授权
            }

            @Override
            public void onGranted(UsbDevice usbDevice, boolean granted) {
                if (granted) {
                    mUvcCameraProxy.connectDevice(usbDevice);// 连接USB设备
                }
            }

            @Override
            public void onConnected(UsbDevice usbDevice) {
                mUvcCameraProxy.openCamera(); // 打开相机
            }

            @Override
            public void onCameraOpened() {
                //预览
            }

            @Override
            public void onDetached(UsbDevice usbDevice) {
                mUvcCameraProxy.closeCamera(); // 关闭相机
            }
        });
    }


    private void initListener() {
        mBtnHwCamera.setOnClickListener(view -> {
            //查找usb相机设备，会在onAttached里回调
            mUvcCameraProxy.checkDevice();

            mUvcCameraProxy.isCameraOpen();//是否已经打开相机

            //红外拍照
            mUvcCameraProxy.takePicture();
        });
        mBtnLightCamera.setOnClickListener(view -> {
            //常规
            Intent intent = new Intent();
            mLightFilePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/lightCamera.png";
            intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
            Uri uri = Uri.fromFile(new File(mLightFilePath));
            // 输出图片指定路径
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            startActivityForResult(intent, LIGHT_OPEN_CAMERA_CODE);
        });
        mBtnFusion.setOnClickListener(view -> {
            if (mLightBitmap != null && mHwBitmap != null) {
                //融合
                mFusionBitmap = ImageFusionUtil.compoundBitmap(mHwBitmap, mLightBitmap);
                mImgFusion.setImageBitmap(mFusionBitmap);
            } else {
                Toast.makeText(this, "请先补全相机照片再进行融合!", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == LIGHT_OPEN_CAMERA_CODE) {
            FileInputStream lightInputStream = null;
            try {
                lightInputStream = new FileInputStream(mLightFilePath);
                mLightBitmap = BitmapFactory.decodeStream(lightInputStream);
                if (mLightBitmap != null) {
                    mImgLight.setImageBitmap(mLightBitmap);
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } finally {
                if (lightInputStream != null) {
                    try {
                        lightInputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    private void initView() {
        mBtnHwCamera = findViewById(R.id.btn_hw_camera);
        mBtnLightCamera = findViewById(R.id.btn_light_camera);
        mBtnFusion = findViewById(R.id.btn_fusion);

        mImgHw = findViewById(R.id.img_hw);
        mImgLight = findViewById(R.id.img_light);
        mImgFusion = findViewById(R.id.img_fusion);
    }

    private void checkPermission() {
        //所有的权限列表
        List<String> permissions = new ArrayList<>();
        permissions.add(Manifest.permission.CAMERA);
        permissions.add(Manifest.permission.READ_EXTERNAL_STORAGE);
        permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);

        //未获取的权限列表
        List<String> notGrantedList = new ArrayList<>();
        for (int i = 0; i < permissions.size(); i++) {
            String permission = permissions.get(i);
            int ret = ContextCompat.checkSelfPermission(this, permission);
            if (ret != PackageManager.PERMISSION_GRANTED) {
                notGrantedList.add(permission);
            }
        }

        //申请未获取的权限
        int notGrantedCount = notGrantedList.size();
        if (notGrantedCount > 0) {
            String[] permissionArr = notGrantedList.toArray(new String[notGrantedCount]);
            ActivityCompat.requestPermissions(this, permissionArr, 0);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mUvcCameraProxy.unregisterReceiver(); //注销USB插拔监听广播
    }
}